#!/bin/bash

KERNEL_DIR='./linux-6.7.6'
CGDB='/opt/riscv64/bin/riscv64-linux-gnu-gdb'
if [ ! -x "${CGDB}" ] ; then
	CGDB='/opt/riscv64-lp64d--glibc--stable-2023.08-1/bin/riscv64-buildroot-linux-gnu-gdb'
fi
if [ ! -x "${CGDB}" ] ; then
	echo "Error, cross gdb not found: \"${CGDB}\"." 1>&2
	exit 1
fi
if [ ! -d "${KERNEL_DIR}" ] ; then
	echo "Error, linux kernel not found: \"${KERNEL_DIR}\"." 1>&2
	exit 2
fi

cd "${KERNEL_DIR}" || exit 3
if [ ! -f './vmlinux' ] ; then
	echo 'Error, vmlinux not found.' 1>&2
	exit 4
fi

VMGDBPY="$(realpath ./scripts/gdb/vmlinux-gdb.py)"
CFGDIR="$HOME/.config/gdb"
if [ ! -f "${CFGDIR}/gdbinit" ] ; then
	mkdir -p "${CFGDIR}"
	touch "${CFGDIR}/gdbinit"
fi
if [ "$(< ${CFGDIR}/gdbinit)" != "add-auto-load-safe-path ${VMGDBPY}" ] ; then
	echo "add-auto-load-safe-path ${VMGDBPY}" > "${CFGDIR}/gdbinit"
fi

export PYTHONPATH="$PWD/scripts/gdb"
# invoke cross gdb executable
exec "${CGDB}" -q \
	-ex 'file ./vmlinux' \
	-ex "source ${VMGDBPY}" \
	-ex 'target remote :2023' \
	-ex 'hbreak start_kernel' \
	-ex 'continue'

exit 5
